//
//  turntableView.m
//  yunbaolive
//
//  Created by IOS1 on 2019/6/5.
//  Copyright © 2019 cat. All rights reserved.
//

#import "turntableView.h"
#import "turntableRuleView.h"
#import "turntableRecordView.h"
#import "turntableResultView.h"

@implementation turntableView{
    UIView *bottomView;
    UIImageView *turntableImgView;
    UIButton *startButton;
    NSDictionary *awards;
    NSArray *levellist;
    NSArray *turngiftlist;
    CGFloat startValue;
    CGFloat endValue;
    int resultIndex;
    NSMutableArray *typeBtnArray;
    NSDictionary *typeDic;
    
    UIImageView *priceView;
    UILabel *priceLabel;
    
    turntableRuleView *ruleView;
    turntableRecordView *recordView;
    turntableResultView *resultView;
    NSArray *resultGiftArray;

}
- (void)dodissmiss{
    [UIView animateWithDuration:0.3 animations:^{
        bottomView.y = _window_height;
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];

}
- (void)show{
    self.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
//        bottomView.y = _window_height * 0.33 - ShowDiff;
        bottomView.y = _window_height -447 ;//- ShowDiff;

    }];

}
-(instancetype)init{
    if (self = [super init]) {
        self.frame = CGRectMake(0, 0, _window_width, _window_height);
        startValue = 0;
        [self creatUI];
    }
    return self;
}
- (void)creatUI{
    UIButton *button = [UIButton buttonWithType:0];
//    button.frame = CGRectMake(0, 0, _window_width, _window_height * 0.33 - ShowDiff);
    
    button.frame = CGRectMake(0, 0, _window_width, _window_height -447);

    [button addTarget:self action:@selector(dodissmiss) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
//    bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, _window_height * 0.67 + ShowDiff)];
    bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, 447)];

    bottomView.backgroundColor = [UIColor clearColor];
    [self addSubview:bottomView];
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _window_width, bottomView.height)];
    imageV.contentMode = UIViewContentModeScaleAspectFill;
    imageV.image = [UIImage imageNamed:@"turntable_转盘背景"];
    [bottomView addSubview:imageV];
    
    UIImageView *ddd = [[UIImageView alloc]init];
    ddd.image = [UIImage imageNamed:@"大转盘底座"];
    [bottomView addSubview:ddd];

    UIImageView *yinyingImageView = [[UIImageView alloc]init];
    yinyingImageView.image = [UIImage imageNamed:@"turntable_转盘阴影"];
    [bottomView addSubview:yinyingImageView];
    [yinyingImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomView);
        make.width.equalTo(bottomView).multipliedBy(0.89);
        make.centerY.equalTo(bottomView).multipliedBy(0.915);
        make.height.equalTo(yinyingImageView.mas_width);
    }];
    
    turntableImgView = [[UIImageView alloc]init];
    turntableImgView.image = [UIImage imageNamed:@"turntable_转盘_new"];
    [bottomView addSubview:turntableImgView];
    [turntableImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(yinyingImageView);
        make.width.equalTo(bottomView).multipliedBy(0.73);
        make.height.equalTo(turntableImgView.mas_width);
    }];
    UIImageView *turntableBack = [[UIImageView alloc]init];
    turntableBack.image = [UIImage imageNamed:@"turntable_转盘3"];
    [bottomView addSubview:turntableBack];
    [turntableBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(turntableImgView);
        make.width.equalTo(turntableImgView).multipliedBy(1.15);
        make.height.equalTo(turntableImgView).multipliedBy(1.15);

    }];

    [ddd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(turntableImgView.mas_centerY);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-50);
        make.centerX.equalTo(bottomView);
        make.width.equalTo(self).multipliedBy(0.55);
    }];

    awards = @{
               @"0": @[
                       @{
                           @"min": @4,
                           @"max":@41
                           },
                       ],
               @"1":@[
                       @{
                           @"min": @49,
                           @"max":@86
                           }
                       ],

                @"2":@[
                       @{
                           @"min": @94,
                           @"max":@131
                           }
                       ]    ,
               @"3":@[
                       @{
                           @"min": @139,
                           @"max":@176
                           }
                       ],

               @"4": @[
                       @{
                           @"min": @184,
                           @"max":@221
                           }
                       ],
               @"5":@[
                       @{
                           @"min": @229,
                           @"max":@266
                           }
                       ],
               @"6":@[
                       @{
                           @"min": @274,
                           @"max":@311
                           }
                       ],
               @"7":@[
                       @{
                           @"min": @319,
                           @"max":@356
                           }
                       ]

                };
    [bottomView layoutIfNeeded];
    [self requestData];

    [UIView animateWithDuration:0.3 animations:^{
        bottomView.y = button.bottom;
    }];
}
- (void)requestData{
    [WYNetworking postWithUrl:@"Turntable.GetTurntable" Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            levellist = [infoDic valueForKey:@"config"];
            turngiftlist = [infoDic valueForKey:@"list"];
            [self creatLastView];
        }
    } Fail:^(id fail) {
        
    }];
}
- (void)creatLastView{
    for (int i = 0; i < turngiftlist.count; i++) {

        NSDictionary *dic = turngiftlist[i];
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(turntableImgView.width/2-60, 0, 120, turntableImgView.width)];
        [turntableImgView addSubview:view];
        
        
        UIImageView *ImgV = [[UIImageView alloc]init];
        ImgV.contentMode = UIViewContentModeScaleAspectFit;
        [view addSubview:ImgV];
        if ([minstr([dic valueForKey:@"type"]) isEqual:@"2"]) {
            [ImgV sd_setImageWithURL:[NSURL URLWithString:minstr([dic valueForKey:@"thumb"])]];
            [ImgV mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(view);
                make.centerY.equalTo(view).multipliedBy(0.45);
                make.width.height.mas_equalTo(35);
            }];

        }else{
            UILabel *label = [[UILabel alloc]init];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            [view addSubview:label];
            NSString *nameStr = minstr([dic valueForKey:@"type_val"]);
            
            if ([minstr([dic valueForKey:@"type"]) isEqual:@"0"]) {
                label.font = [UIFont boldSystemFontOfSize:12];
                label.numberOfLines = 0;
                label.text = YZMsg(@"再接再厉");
                [label mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(view);
                    make.centerY.equalTo(view).multipliedBy(0.5);
                    
                }];
                
            }else{
                label.text = nameStr;
                label.font = [UIFont systemFontOfSize:10];
//                ImgV.image = [UIImage imageNamed:@"logFirst_钻石"];
                [ImgV sd_setImageWithURL:[NSURL URLWithString:minstr([dic valueForKey:@"thumb"])]];

                [ImgV mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(view);
                    make.centerY.equalTo(view).multipliedBy(0.45);
                    make.width.height.mas_equalTo(30);
                }];
                
                [label mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(view);
                    make.height.mas_equalTo(20);
                    make.top.equalTo(ImgV.mas_bottom);
                }];
                
            }

        }
        if (minstr([dic valueForKey:@"thumb"]).length > 6) {

        }else{
            
            
        }

//        if (i != 0) {
            NSDictionary *radiusDic = [[awards valueForKey:[NSString stringWithFormat:@"%d",i]] firstObject];
            CGFloat aa = ([minstr([radiusDic valueForKey:@"max"]) floatValue] - [minstr([radiusDic valueForKey:@"min"]) floatValue])/2+[minstr([radiusDic valueForKey:@"min"]) floatValue];
            view.transform = CGAffineTransformMakeRotation(radians(aa));
//        }
    }
    startButton = [UIButton buttonWithType:0];
//    startButton.size = CGSizeMake(_window_width*0.2, _window_width*0.2);
//    startButton.center = turntableImgView.center;
    [startButton setImage:[UIImage imageNamed:getImagename(@"turntable_开始指针")] forState:0];
    [startButton addTarget:self action:@selector(startButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:startButton];
    [startButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(turntableImgView);
        make.width.equalTo(bottomView).multipliedBy(0.32);
        make.height.equalTo(startButton.mas_width);
    }];

    typeBtnArray = [NSMutableArray array];
    typeDic = levellist[0];
//    CGFloat hhhhhh = startButton.bottom + 20;
    for (int i = 0 ; i < levellist.count; i ++) {
        NSDictionary *dic = levellist[i];
        UIButton *btn = [UIButton buttonWithType:0];
        btn.titleLabel.font = [UIFont systemFontOfSize:13];
        btn.titleLabel.numberOfLines = 2;
        btn.titleLabel.textColor = [UIColor whiteColor];
        [btn setAttributedTitle:[self buttonAttributedString:[NSString stringWithFormat:YZMsg(@"转%@次"),minstr([dic valueForKey:@"times"])] andCoin:minstr([dic valueForKey:@"coin"])] forState:0];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [btn setBackgroundImage:[UIImage imageNamed:@"turntable_btn_sel"] forState:UIControlStateSelected];
        [btn setBackgroundImage:[UIImage imageNamed:@"turntable_btn_nor"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(typeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 10086+i;
        btn.selected = NO;
        [bottomView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(bottomView).multipliedBy(1.81);
        make.left.equalTo(bottomView).offset(_window_width*0.04+i*(_window_width*0.32));
            make.width.mas_equalTo(_window_width *0.28);
            make.height.equalTo(btn.mas_width).multipliedBy(0.43);
        }];
        [typeBtnArray addObject:btn];
        if (i == 0) {
            btn.selected = YES;
        }
//        if (i == 0) {
//            priceView = [[UIImageView alloc]initWithFrame:CGRectMake(btn.x+btn.width*0.135, btn.top - btn.height*0.6, btn.width*0.73, btn.height * 0.7)];
//            priceView.image = [UIImage imageNamed:@"turntable_price"];
//            [bottomView addSubview:priceView];
//            priceView.hidden = YES;
//            priceLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, priceView.width, priceView.height * 0.9)];
//            priceLabel.font = [UIFont systemFontOfSize:11];
//            priceLabel.textAlignment = NSTextAlignmentCenter;
//            [priceView addSubview:priceLabel];
//            [PublicObj lineViewWithFrame:CGRectMake(0, btn.bottom, _window_width, 1) andColor:RGB_COLOR(@"#343535", 1) andView:bottomView];
//            hhhhhh = (btn.bottom+1);
//        }
    }
    NSArray *array = @[YZMsg(@"游戏规则"),YZMsg(@"中奖记录")];
    for (int i = 0; i < array.count; i ++) {
        UIButton *buton = [UIButton buttonWithType:0];
        buton.frame = CGRectMake(15 + i * (_window_width-80-15), 20, 64, 24);
        [buton setTitle:array[i] forState:0];
//        [buton setBackgroundColor:[[UIColor blackColor]colorWithAlphaComponent:0.2]];
        [buton setTitleColor:[UIColor whiteColor] forState:0];
        buton.titleLabel.font = SYS_Font(11);
        buton.layer.cornerRadius = 12.0;
        buton.layer.borderWidth = 1;
        buton.layer.borderColor = [UIColor whiteColor].CGColor;
        buton.layer.masksToBounds = YES;
        [buton addTarget:self action:@selector(bottomButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        buton.tag = 7655 + i;
        [bottomView addSubview:buton];
    }

}
//角度转弧度
double radians(float degrees) {
    return degrees*M_PI/180;
}
- (void)startButtonClick{
//    if (typeDic) {
        [self requestReasult];
        
//    }else{
//        [MBProgressHUD showError:@"请选择转盘价格"];
//    }
}
- (void)requestReasult{
    startButton.userInteractionEnabled = NO;
    
    [WYNetworking postWithUrl:@"Turntable.Turn" Dic:@{@"id":minstr([typeDic valueForKey:@"id"]),@"liveuid":minstr([_zhuboMsg valueForKey:@"uid"]),@"stream":minstr([_zhuboMsg valueForKey:@"stream"])} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSDictionary *rDic = [info firstObject];
            [Config saveUserCoin:minstr([rDic valueForKey:@"coin"])];
            
            resultGiftArray = [rDic valueForKey:@"list"];
            resultIndex = 0;
            NSDictionary *infoDic;
            if ([resultGiftArray count] > 0) {
                infoDic = [resultGiftArray lastObject];
                if (self.delegate) {
                    [self.delegate turntableZhongjianla];
                }
            }else{
                infoDic = @{@"type":@"0"};
            }
            for (int i = 0; i < turngiftlist.count; i ++) {
                NSDictionary *dic = turngiftlist[i];
                if ([minstr([infoDic valueForKey:@"type"]) isEqual:@"0"]) {
                    if ([minstr([dic valueForKey:@"type"]) isEqual:@"0"]) {
                        resultIndex = i;
                    }
                    
                }else{
                    if ([minstr([infoDic valueForKey:@"id"]) isEqual:minstr([dic valueForKey:@"id"])]) {
                        resultIndex = i;
                    }
                }
            }
            //resultIndex = arc4random()%8;
            
            endValue = [self fetchResult];
            CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
            rotationAnimation.delegate = self;
            rotationAnimation.fromValue = @(startValue);
            rotationAnimation.toValue = @(endValue);
            rotationAnimation.duration = 3.0f;
            rotationAnimation.autoreverses = NO;
            rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            rotationAnimation.removedOnCompletion = NO;
            rotationAnimation.fillMode = kCAFillModeBoth;
            [turntableImgView.layer addAnimation:rotationAnimation forKey:@"revItUpAnimation"];
            
        }else{
            startButton.userInteractionEnabled = YES;
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        startButton.userInteractionEnabled = YES;
        [MBProgressHUD showError:YZMsg(@"网络错误")];
    }];
    
}
- (CGFloat)fetchResult{
    srand((unsigned)time(0));
    float random;
    for (NSString *str in [awards allKeys]) {
        if ([str intValue] == resultIndex) {
            int bb;
            if (resultIndex == 0) {
                bb = arc4random()%2;
            }else{
                bb = 0;
            }
            NSDictionary *content = awards[str][bb];
            int min = [content[@"min"] intValue];
            int max = [content[@"max"] intValue];
            srand((unsigned)time(0));
            random = rand() % (max - min) +min;
        }
    }
//    return radians(random + 360*5);
    return (M_PI*2 - radians(random)) + M_PI*2*5;

}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    startButton.userInteractionEnabled = YES;

    startValue = endValue;
    
    if (startValue >= endValue) {
        startValue = startValue - radians(360*10);
    }
    
    NSLog(@"startValue = %f",startValue);
    NSLog(@"endValue = %f\n",endValue);
//    if (resultIndex == 0) {
//        [MBProgressHUD showError:@"谢谢参与，再接再厉"];
//    }else{
        if (resultView) {
            [resultView removeFromSuperview];
            resultView = nil;
        }
//        NSArray *aaa = @[@"",@"",@"",@"",@"",@""];
    if (resultGiftArray.count > 0) {
        resultView = [[turntableResultView alloc]initWithResultArray:resultGiftArray];
        [self addSubview:resultView];
    }
//        [MBProgressHUD showError:[NSString stringWithFormat:@"恭喜你，获得%@",minstr([turngiftlist[resultIndex] valueForKey:@"giftname"])]];
//    }
}
#pragma mark ============jiage=============
- (void)typeBtnClick:(UIButton *)sender{
//    if (sender.selected) {
//        typeDic = nil;
//        sender.selected = NO;
//        sender.imageView.transform = CGAffineTransformMakeScale(1, 1);
//        priceView.hidden = YES;
//        return;
//    }
    for (int i = 0; i < typeBtnArray.count; i ++) {
        UIButton *btn = typeBtnArray[i];
        if (btn == sender) {
            btn.selected = YES;
            typeDic = levellist[i];
//            btn.imageView.transform = CGAffineTransformMakeScale(2, 2);
//            priceLabel.text = [NSString stringWithFormat:@"%@%@",minstr([typeDic valueForKey:@"coin"]),[common name_coin]];
//            priceView.centerX = btn.centerX;
//            priceView.hidden = NO;
        }else{
            btn.selected = NO;
//            btn.imageView.transform = CGAffineTransformMakeScale(1, 1);
        }
    }
}

- (void)bottomButtonClick:(UIButton *)sender{
    if (sender.tag == 7655) {
        if (!ruleView) {
            ruleView = [[turntableRuleView alloc]init];
            [self addSubview:ruleView];
        }else{
            ruleView.hidden = NO;
            [ruleView show];
        }
    }else{
        if (!recordView) {
            recordView = [[turntableRecordView alloc]init];
            [self addSubview:recordView];
        }else{
            recordView.hidden = NO;
            [recordView show];
        }

    }
}
- (NSAttributedString *)buttonAttributedString:(NSString *)name andCoin:(NSString *)coin{
    NSString *btnNameStr1 =   [NSString stringWithFormat:@"%@\n%@%@",name,coin,[common name_coin]];
    NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:btnNameStr1];
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
                           value:[[UIColor whiteColor] colorWithAlphaComponent:0.5]
                           range:NSMakeRange(name.length, btnNameStr1.length-name.length)];
    [AttributedStr1 addAttribute:NSFontAttributeName
                           value:[UIFont systemFontOfSize:10]
                           range:NSMakeRange(name.length, btnNameStr1.length-name.length)];
    
    return AttributedStr1;

}
@end
